// store.js
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios' //使用 axios 作为 HTTP 客户端
import router from '../router' // 引入 Vue 路由器
import { Message } from 'element-ui' // 使用 Element UI

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    rolesList: JSON.parse(sessionStorage.getItem('roles')) || [],
    userData: JSON.parse(sessionStorage.getItem('userData')) || null,
    token: sessionStorage.getItem('token') || null,
  },
  mutations: {
    setLoading(state, loading) {
      state.loading = loading
    },
    setRolesList(state, roles) {
      // 添加一个 mutation 来更新角色列表
      state.rolesList = roles
      sessionStorage.setItem('roles', JSON.stringify(roles))
    },
    setUserData(state, userData) {
      state.userData = userData
      sessionStorage.setItem('userData', JSON.stringify(userData))
    },
    setToken(state, token) {
      state.token = token
      sessionStorage.setItem('token', token)
    },
  },
  actions: {
    login({ commit }, loginForm) {
      axios
        .post('login', loginForm)
        .then(({ data: res }) => {
          if (res.meta.status === 200) {
            commit('setUserData', res.data)
            commit('setToken', res.data.token)
            window.sessionStorage.setItem('token', res.data.token)
            router.push('/home')
            Message.success('登录成功')
          } else {
            Message.error('登录失败！')
          }
        })
        .catch((error) => {
          Message.error('登录请求失败！')
        })
    },
    getRolesList({ commit }) {
      // 添加一个 action 来获取角色列表
      axios
        .get('roles')
        .then(({ data: res }) => {
          if (res.meta.status === 200) {
            commit('setRolesList', res.data)
          } else {
            Message.error('获取角色列表失败')
          }
        })
        .catch((error) => {
          Message.error('获取角色列表请求失败')
        })
    },
  },
  getters: {
    // firstName: (state) => {
    //   return state.userData.username[0]
    // },
    // roleName: (state) => {
    //   let cs = ''
    //   state.rolesList.forEach((role) => {
    //     if (role.id === state.userData.rid) {
    //       cs = role.roleDesc
    //     }
    //     if (state.userData.rid === 0) {
    //       cs = '超级管理员'
    //     }
    //   })
    //   return cs
    // },
    userInfo: (state) => {
      const obj = {
        ...state.userData,
        firstName: state.userData.username[0],
        roleName: state.userData.rid === 0 ? '超级管理员' : '',
      }
      // state.rolesList.forEach((role) => {
      //   if (role.id === state.userData.rid) {
      //     obj.roleName = role.roleDesc
      //   }
      // })
      const role = state.rolesList.find((role) => {
        return role.id === state.userData.rid
      })
      if (role) {
        obj.roleName = role.roleDesc
      }
      return obj
    },
  },
})
